package com.secxiot.consumer.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.entity.ExceptionInfo;
import com.secxiot.common.exception.BaseRuntimeException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ExceptionDecoder implements ErrorDecoder {

    Logger log = LoggerFactory.getLogger(ExceptionDecoder.class);

    @Override
    public Exception decode(String s, Response response) {

        try {
            if (response.body() != null) {
                String body = Util.toString(response.body().asReader());
                log.error(body);
                ExceptionInfo exceptionInfo = JSON.parseObject(body, new TypeReference<ExceptionInfo>() {
                });
                log.error("Feign异常：\n" + JSON.toJSONString(exceptionInfo));
                String message = exceptionInfo.getMessage();
                String[] split = message.split("\\|");
                if (split.length == 2) {
                    return new BaseRuntimeException(ServerStatusEnum.getByStatus(Integer.parseInt(split[0])));
                } else {
                    Class clazz = Class.forName(exceptionInfo.getException());
                    return (Exception) clazz.getDeclaredConstructor(String.class)
                            .newInstance(exceptionInfo.getMessage());
                }

            }
        } catch (Exception var4) {
            log.error(var4.getMessage());
            return new InternalException(var4.getMessage());
        }
        return new InternalException("系统异常,请联系管理员");
    }
}
